from microbit import *

TX = pin8
RX = pin12

class Logger(object):
    def __init__(self) -> None:
        self.text = ''
        
    def add(self, v, prefix = ''):
        self.text = self.text + v + prefix
    
    def getLatest(self):
        r = self.text
        self.clear()
        return r
    
    def clear(self):
        self.text = ''

class IOT(object):
    def __init__(self):
        global TX,RX
        self.logger = Logger()
        self.mqttRecv=""
        self.__userToken = ""
        self.__topic = ""
        uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=TX, rx=RX)
        self.__sendAT("AT+RESTORE", 1000)
        self.__sendAT("AT+RST", 1000)
        self.__sendAT("AT+CWMODE=1", 500)
        self.__sendAT("AT+SYSTIMESTAMP=1634953609130", 100)
        self.__sendAT("AT+CIPSNTPCFG=1,8,'ntp1.aliyun.com'", 100)

        # 读取前面的初始化串口输出
        timeOut = running_time()
        uart_str = ''
        while True:
            display.scroll('R')
            if uart.any():
                uart_str: str = str(uart.read(), 'UTF-8') + uart_str
                self.logger.add(uart_str)
            elif running_time() - timeOut > 8000:
                display.scroll("INIT END")
                break

    def __sendAT(self, command: str, wait: int = 0):
        uart.write(command + "\u000D\u000A")
        sleep(wait)

    def __waitResponse(self):
        uart_str = ""
        timeOut = running_time()
        display.scroll("WAIT")
        while True:
            # display.scroll('R')
            if uart.any():
                uart_str: str = str(uart.read(), 'UTF-8') + uart_str
                self.logger.add(uart_str)
                if "WIFI GOT IP" in uart_str:
                    display.scroll('IP')
                    return True
                elif "OK" in uart_str:
                    display.scroll('OK')
                    return True
                elif "FAIL" in uart_str:
                    display.scroll('FAIL')
                    return False
                elif "CONNECT" in uart_str:
                    display.scroll('CONNECT')
                    return True
                elif len(uart_str) > 60:
                    uart_str = ""
            elif running_time() - timeOut > 8000:
                display.scroll('OUT')
                return False
            
            
    def scanWIFI(self):
        display.scroll("SCAN")
        self.__sendAT("AT+CWLAP", 500)
        return self.__waitResponse()

    def connectWIFI(self, ssid: str, pw: str):
        display.scroll("CCCC")
        uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=TX, rx=RX)
        sleep(200)
        self.__sendAT("AT+CWJAP=\"" + ssid + "\",\"" + pw + "\"", 500)
        return self.__waitResponse()

    def connectKidsiot(self, userToken:str, topic:str):
        self.__userToken = userToken
        self.__topic = topic
        display.scroll('KKKK:')
        self.__sendAT("AT+CIPSTART=\"TCP\",\"139.159.161.57\",5555", 5000)
        toSendStr = "{\"topic\":\"" + self.__topic + "\",\"userToken\":\"" + self.__userToken + "\",\"op\":\"init\"}"
        self.__sendAT("AT+CIPSEND="+str(len(toSendStr)+2), 500)
        self.__sendAT(toSendStr, 100)
        return self.__waitResponse()

    def uploadKidsiot(self,data:str):
        display.scroll('UUUU:')
        toSendStr = "{\"topic\":\"" + self.__topic + "\",\"userToken\":\"" + self.__userToken + "\",\"op\":\"up\",\"data\":\"" + data + "\"}"
        self.__sendAT("AT+CIPSEND="+str(len(toSendStr)+2), 500)
        self.__sendAT(toSendStr, 100)
        display.scroll('TCP END')

    def disconnectKidsiot(self):
        toSendStr = "{\"topic\":\"" + self.__topic + "\",\"userToken\":\"" + self.__userToken + "\",\"op\":\"close\"}"
        self.__sendAT("AT+CIPSEND="+str(len(toSendStr)+2), 500)
        self.__sendAT(toSendStr, 100)